import { Alert } from "react-native";
import { BackAndroid } from "react-native";
import { setJSExceptionHandler, setNativeExceptionHandler } from "react-native-exception-handler";
import ToastUtil from '../utils/toast';
import HTTP from '../utils/http';

let errorAlertShow;
const errorHandler = (e) => {
  if (errorAlertShow) return;
  errorAlertShow = true;
  HTTP.errLogCollect({ url: 'errorHandler', err: e.toString() });
  Alert.alert(
    "抱歉，执行出现异常",
    `
    Error: ${e}
    
    请退出进程重启!
    `,
    [
      {
        text: "关 闭",
        onPress: () => {
          errorAlertShow = false;
          BackAndroid.exitApp();
        }
      }
    ], { cancelable: false }
  )
};

class ExceptionHandler {

  init () {
    setJSExceptionHandler(errorHandler);

    setNativeExceptionHandler(errorString => {
      ToastUtil.showError(errorString)
    });
  }

}

module.exports = new ExceptionHandler();

